<template>


  <div class="standard-detail-container">
    <!-- 头部信息 -->
    <div class="detail-header">
      <!-- 第一行：左边是标题，右边是标签 -->
      <div class="header-first-row">
        <h1 class="standard-title">{{ detailData.title }}</h1>
        <!-- <div class="tags-container">
            <span v-for="(tag, tagIndex) in detailData.baseBusinessIndusty" :key="tagIndex" class="tilted-tag">
              <span class="tag-text">{{ tag.name }}</span>
            </span>
         </div>  -->
      </div>

      <!-- 第二行：浏览量和标准号在左边，发布日期和实施日期在右边 -->
      <div class="header-second-row">
        <div class="left-info">
          预览文件
        </div>
        <div class="zhongjian-info">
          <span class="view-count"><i style="margin-right: 3px;" class="el-icon-view"></i>浏览量 {{ detailData.browseNum
            }}</span>
          <div class="standard-number">{{ detailData.normCode }}</div>
          <span class="publish-date">发布日期 {{ detailData.publishDate }}</span>
          <span class="implement-date">实施日期 {{ detailData.implementDate }}</span>
        </div>
        <div class="right-info">
          <ebutton @click="downloadFile" v-if="detailData.standarsPath != null"
            class="resetbutton2"><i class="el-icon-bottom" ></i>下载文件</ebutton>
          <button  class="resetbutton2" v-else>暂无文件</button>

        </div>
      </div>
    </div>
    <!-- 预览 -->
    <div v-if="detailData.standarsPath != null" class="auto-pdf-preview">
      <div v-if="autoPreviewLoading" class="preview-loading">
        <div :fullscreen="false" text="文件加载中..."></div>
      </div>
      <div v-else-if="autoPdfPreviewUrl" class="auto-pdf-wrapper">
        <PDFViewer :pdfUrl="autoPdfPreviewUrl" />
      </div>
      <div v-else class="preview-error">
        <p>文件加载失败，请点击上方预览按钮尝试</p>
      </div>
    </div>
    <!-- 预览文件 -->
    <!-- 主要内容 -->
    <!-- <div class="detail-content">
      <div class="content-section">
        <div class="description-section">
          <p v-if="parsedDescription.baseInfo" class="description-item">{{ parsedDescription.baseInfo }}</p>
          <p v-if="parsedDescription.draftingUnits" class="description-item">
            <span class="description-label">主要起草单位：</span>
            <span>{{ parsedDescription.draftingUnits }}</span>
          </p>
          <p v-if="parsedDescription.drafters" class="description-item">
            <span class="description-label">主要起草人：</span>
            <span>{{ parsedDescription.drafters }}</span>
          </p>
        </div>
      </div>
    </div> -->
    <!-- 主要内容 起草人 -->

    <!-- 新增下载模块 -->
    <!-- <div class="download-section">
      
      <el-popover 
        placement="top-start" 
        title="详情" 
        width="800" 
        trigger="hover" 
        v-if="detailData.standarsPath != null">
         
          <div v-if="parsedDescription">
            <p style="color: #000000; margin: 5px 0;">基本信息：{{ parsedDescription.baseInfo || '暂无数据' }}</p>
            <p style="color: #000000; margin: 5px 0;">起草单位：{{ parsedDescription.draftingUnits || '暂无数据' }}</p>
            <p style="color: #000000; margin: 5px 0;">起草人：{{ parsedDescription.drafters || '暂无数据' }}</p>
          </div>
          <p v-else style="color: #000000; margin: 5px 0;">parsedDescription 对象未定义</p>
        
    
        <div class="download-header" style="display: flex;align-items: center;justify-content: space-between;" slot="reference"> 
          <h3 class="download-title">{{ detailData.standarsPath }}.PDF</h3> 
          <div> 
            <el-button type="primary" @click="downloadFile" icon="el-icon-download">下载文件</el-button> 
           
          </div> 
        </div>
      </el-popover>
      
  
      <div v-else class="download-header" style="display: flex;align-items: center;justify-content: space-between;">
        <h3 class="download-title">暂无文件</h3>
        <div>
        
        </div>
      </div>

      
    </div> -->

    <!-- 自动PDF预览区域 -->


    <!-- PDF 预览模态框 -->
    <el-dialog title="PDF 预览" :visible.sync="dialogVisible" width="90%" height="90%" :close-on-click-modal="false">
      <div class="pdf-preview-wrapper" style="height: 70vh;">
        <PDFViewer :pdfUrl="pdfPreviewUrl" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GuoChanpinxq, DownloadFilePdf } from '@/api/user'
import vueOneconfig from '../../vue.config'
import PDFViewer from '@/components/PDFViewer.vue' // 导入PDFViewer组件

export default {
  components: {
    PDFViewer // 注册PDFViewer组件
  },
  data() {
    return {
      detailData: {},
      standardId: "",
      vueOneconfig: "",
      dialogVisible: false, // 控制模态框显示
      pdfPreviewUrl: '', // PDF预览URL
      previewLoading: false,
      normCodefile: "",
      autoPdfPreviewUrl: '', // 自动预览的PDF URL
      autoPreviewLoading: false // 自动预览加载状态
    };
  },
  created() {
    // 在组件创建时，初始化vueOneconfig
    this.vueOneconfig = vueOneconfig.devServer.proxy["/api"].target;
  },
  mounted() {
    // 在组件挂载后，可以根据实际情况加载数据
    // 例如从路由参数中获取id，然后调用API获取详情
    this.standardId = this.$route.query.id;

    const id = this.$route.query.id;
    if (id) {
      // 根据id加载详情数据
      this.loadDetailData(id)
    }
  },
  computed: {
    // 解析description字段，按格式拆分显示
    parsedDescription() {
      const description = this.detailData.description || '';
      const result = {
        baseInfo: '',
        draftingUnits: '',
        drafters: ''
      };

      // 提取主要起草单位
      const unitsMatch = description.match(/主要起草单位([^。]*)/);
      if (unitsMatch && unitsMatch[1]) {
        result.draftingUnits = unitsMatch[1].replace(/[：:]/, '').trim();
      }

      // 提取主要起草人
      const draftersMatch = description.match(/主要起草人([^。]*)/);
      if (draftersMatch && draftersMatch[1]) {
        result.drafters = draftersMatch[1].replace(/[：:]/, '').trim();
      }

      // 提取基础信息（去掉主要起草单位和主要起草人部分）
      let baseInfo = description;
      if (unitsMatch) {
        baseInfo = baseInfo.replace(/主要起草单位[^。]*。/, '').trim();
      }
      if (draftersMatch) {
        baseInfo = baseInfo.replace(/主要起草人[^。]*。?/, '').trim();
      }

      // 确保基础信息以句号结尾
      if (baseInfo && !baseInfo.endsWith('。')) {
        baseInfo += '。';
      }

      result.baseInfo = baseInfo;

      return result;
    }
  },
  methods: {
    loadDetailData(id) {
      // 调用API获取数据
      GuoChanpinxq(id).then(res => {
        this.detailData = res.data
        this.normCodefile = res.data.normCode

        // 当数据加载完成后，如果有standarsPath，则自动加载PDF进行预览
        if (res.data.standarsPath) {
          this.autoLoadPDF();
        }
      }).catch(err => {
        console.error('获取详情失败:', err)
      })
    },

    // ... existing code ...
    downloadFile() {
      // 调用API下载文件
      DownloadFilePdf({ id: this.standardId }).then(res => {
        try {
          // 创建Blob对象
          const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          // 创建下载链接
          const link = document.createElement('a');
          const url = URL.createObjectURL(blob);
          link.href = url;
          link.setAttribute('download', this.normCodefile + '.pdf');
          // 添加到DOM并触发点击
          document.body.appendChild(link);
          link.click();

          // 清理资源
          setTimeout(() => {
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
          }, 100);

          this.$message.success('下载成功',1000);
        } catch (err) {
          console.error('下载失败:', err);
          // this.$message.error('下载失败，请重试');
        }
      })
    },
    // ... existing code ...
    // 添加预览文件方法

    // 自动加载PDF文件进行预览
    autoLoadPDF() {
      this.autoPreviewLoading = true;
      try {
        // 调用API获取文件数据
        DownloadFilePdf({ id: this.standardId }).then(response => {
          // 确保我们使用正确的数据
          const blobData = response.data || response;
          // 创建Blob对象
          const blob = new Blob([blobData], { type: 'application/pdf' });
          // 生成URL
          this.autoPdfPreviewUrl = URL.createObjectURL(blob);
          this.autoPreviewLoading = false;
        }).catch(error => {
          console.error('自动加载PDF失败:', error);
          this.autoPreviewLoading = false;
        });
      } catch (error) {
        console.error('自动加载PDF失败:', error);
        this.autoPreviewLoading = false;
      }
    },
    previewFile() {
      this.previewLoading = true;
      try {
        // 调用API获取文件数据
        DownloadFilePdf({ id: this.standardId }).then(response => {
          // 确保我们使用正确的数据
          const blobData = response.data || response;
          // 创建Blob对象
          const blob = new Blob([blobData], { type: 'application/pdf' });
          // 生成URL
          this.pdfPreviewUrl = URL.createObjectURL(blob);
          // 打开模态框
          this.dialogVisible = true;
          this.previewLoading = false;
        }).catch(error => {
          console.error('文件预览失败:', error);
          this.$message.error('PDF加载失败，请重试');
          this.previewLoading = false;
        });
      } catch (error) {
        console.error('文件预览失败:', error);
        this.$message.error('PDF加载失败，请重试');
        this.previewLoading = false;
      }
    },
    // 添加清理方法
    cleanup() {
      // 清理内存引用
      if (this.pdfPreviewUrl) {
        URL.revokeObjectURL(this.pdfPreviewUrl);
        this.pdfPreviewUrl = '';
      }
    }
  }
};
</script>

<style scoped>
/* 全局样式 - 设置背景颜色为#152133 */


/* 主容器样式 - 背景颜色为#04142B，字体颜色为白色 */
.standard-detail-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #04142B;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
  color: white;
  overflow: hidden; /* 禁止上下滚动 */
}

.header-first-row {
  display: flex;
  justify-content: center;
  align-items: center;
}

.tilted-tag {
  display: inline-block;
  border-radius: 0px 0px 0px 0px;
  border: 1px solid #DDDDDD;
  margin: 0 5px;
  font-size: 12px;
  padding: 5px;
  transform: skew(-15deg);
}

.tag-text {
  transform: skew(15deg);
}

/* 头部信息 */
.detail-header {
  padding-bottom: 5px;
  /* margin-bottom: 30px; */
  border-bottom: 2px solid rgba(255, 255, 255, 0.1);
}

/* 第一行样式 */
.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.standard-title {
  margin: 0;
  flex: 1;
}

/* 第二行样式 */
.header-second-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 5px 0;
}

.zhongjian-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.left-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.right-info {
  display: flex;
  align-items: center;
}

/* 描述信息样式 */
.description-section {
  margin-bottom: 20px;
}

.description-item {
  margin: 10px 0;
  line-height: 1.8;
  font-size: 16px;
}

.description-label {
  font-weight: 600;
  color: #fff;
  margin-right: 5px;
}


.standard-title {
  font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
  font-weight: 500;
  font-size: 22px;
  color: white;
  line-height: 1.4;
  flex: 1;
  margin: 0;
  text-align: center;
}

.standard-number {
  font-size: 14px;
  white-space: nowrap;

  font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
  font-weight: 400;
  color: #DDDDDD;
}

/* 浏览量和分类信息 */
.view-info {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.view-count {
  font-size: 14px;
  font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
  font-weight: 400;
  color: rgba(221, 221, 221, 0.87);

}

.category-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  display: inline-block;
  padding: 4px 12px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background-color: rgba(255, 255, 255, 0.1);
  transform: skewX(-5deg);
  border-radius: 2px;
  font-size: 13px;
  font-weight: 500;
}

.tag span {
  color: white;
  transform: skewX(5deg);
  display: inline-block;
}

/* 日期信息 */
.date-info {
  display: flex;
  align-items: center;
  color: white;
  font-size: 14px;
}

.publish-date,
.implement-date {
  display: flex;
  align-items: center;
  font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
  font-weight: 400;
  font-size: 14px;
  color: rgba(221, 221, 221, 0.87);
}

.date-separator {
  margin: 0 15px;
  color: rgba(255, 255, 255, 0.5);
}

/* 内容区域 */
.detail-content {
  color: white;
  line-height: 1.8;
  font-size: 16px;
}

.content-section {
  margin-bottom: 20px;
  padding: 15px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.content-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.content-section p {
  color: white;
}

/* 下载模块样式 */
.download-section {
  margin-top: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  background: linear-gradient(90deg, #1A3B6B 0%, rgba(26, 59, 107, 0) 100%);
}

.download-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 自动PDF预览样式 */
.auto-pdf-preview {
  /* padding: 20px; */
  background-color: rgba(26, 59, 107, 0.3);
  border-radius: 12px;
}

.preview-title {
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
}

.auto-pdf-wrapper {
  height: 710px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  background-color: #ffffff;
  overflow: hidden;
}

.preview-loading {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-error {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ff4d4f;
  font-size: 14px;
}

.download-title {

  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: white;
  padding: 10px 15px;
  border-radius: 4px;
  background: linear-gradient(90deg, #1A3B6B 0%, rgba(26, 59, 107, 0) 100%);
}

/* 按钮样式 - 使用渐变背景 */
:deep(.el-button--primary) {
  background: linear-gradient(180deg, rgba(0, 135, 255, 0.25) 0%, rgba(0, 135, 255, 0.52) 100%) !important;
  border-color: transparent !important;
  color: white !important;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(360deg, #0085FF 0%, rgba(0, 163, 255, 0) 100%) !important;
  border-color: transparent !important;
  color: white !important;
}

/* PDF预览包装器样式 */
.pdf-preview-wrapper {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .standard-detail-container {
    padding: 20px;
    margin: 15px;
  }

  .title-row {
    flex-direction: column;
    align-items: flex-start;
  }

  .standard-title {
    font-size: 18px;
  }

  .standard-number {
    align-self: flex-start;
  }

  .date-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .date-separator {
    display: none;
  }

  .download-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .download-section {
    padding: 15px;
  }
}


/* 下载按钮 */
.resetbutton2 {
  text-align: center;
  line-height: 30px;
  font-size: 12px;
  color: #fff;
  display: flex;
  margin: 0px 10px;

  align-items: center;
  justify-content: center;
  /* background: #182F50; */
  transform: skew(-10deg);



  width: 143px;
height: 36px;
background: linear-gradient( 180deg, #134884 0%, #0C5FB0 100%);
border-radius: 0px 0px 0px 0px;
border: 1px solid;
border-image: linear-gradient(136deg, rgba(44, 223, 232, 1), rgba(26, 154, 219, 1), rgba(26, 154, 217, 1)) 1 1;
}

.resetbutton2 span {
  transform: skew(10deg);
}

/* 移除重置按钮点击时的黑色边框 */
.resetbutton2:focus {
  outline: none !important;
  border: 1px solid #1A9AD9;
  background: #182F50;
}

.resetbutton2:hover {
  /* background: linear-gradient(360deg, #0085FF 0%, rgba(0, 163, 255, 0) 100%);
  border-radius: 0px 0px 0px 0px;
  border: 1px solid;
  border-image: linear-gradient(180deg, rgba(0, 163, 255, 0), rgba(0, 163, 255, 1)) 1 1;
  border-top: none; */
  cursor: pointer;
}
</style>